<template >
  <div id='myMap'></div>
</template>

<script setup>
import {  onMounted, ref } from "vue";
import { useCounterStore } from '@/stores/counter';
import request from "@/utils/request";


const updata = ref({
  vehicleTripId: "",
  latitude: "",
  longitude: "",
  timestamp: 0,
});

const newPoint = ref();
const store = useCounterStore();  // 使用 Vuex Store

const myRoute = ref();
//行程关联价格
const routes = [
  { name: '火车站-学校', startlat: 80.311433, startlng: 41.152732, endlat: 81.303995, endlng: 40.550221 },
  { name: '学校-火车站', startlat: 81.303995, startlng: 40.550221, endlat: 80.311433, endlng: 41.152732 },
  { name: '学校-飞机站', startlat: 81.303995, startlng: 40.550221, endlat: 80.304692, endlng: 41.265477 },
  { name: '飞机站-学校', startlat: 80.304692, startlng: 41.265477, endlat: 81.303995, endlng: 40.550221 },
]


//这里需要做判断暂时先没写
const findRouteByName = (name) => {
  for (let i = 0; i < routes.length; i++) {
    if (routes[i].name === name) {
      myRoute.value = routes[i];
    }
  }
}

findRouteByName(store.skipData.route)



// GL版命名空间为BMapGL
const BMapGL = window.BMapGL;
//添加LBS解析器
const geoc = new BMapGL.Geocoder();
//添加定位
const geolocation = new BMapGL.Geolocation();

// 设置定时器，每30秒钟调用一次fetchData函数
setInterval(() => {
  geolocation.getCurrentPosition(function (r) {
    if (this.getStatus() == BMAP_STATUS_SUCCESS) {
      geoc.getLocation(r.point, (rs) => {
        newPoint.value = rs.point;
        const timestamp = Date.now();
        updata.value.timestamp = timestamp;
        updata.value.latitude = rs.point.lat;
        updata.value.longitude = rs.point.lng;
        updata.value.vehicleTripId = store.skipData.id;
        request.post("/vehicle-trip/vehicleTripLocation/updateLocal", updata.value).then(result => {
          if (result.success) {
            console.log(result.message)
          }
        }
        )
      })
    }
    else {
      alert('failed' + this.getStatus());
    }
  });
}, 30000);



onMounted(() => {

  // 创建Map实例
  const map = new BMapGL.Map("myMap");
  map.centerAndZoom(new BMapGL.Point(myRoute.value.startlat, myRoute.value.startlng), 17);  // 初始化地图,设置中心点坐标和地图级别--塔里木大学
  map.enableScrollWheelZoom(true);     //开启鼠标滚轮缩放

  //添加路线
  const start = new BMapGL.Point(myRoute.value.startlat, myRoute.value.startlng);
  const end = new BMapGL.Point(myRoute.value.endlat, myRoute.value.endlng);
  var driving = new BMapGL.DrivingRoute(map, { renderOptions: { map: map, autoViewport: true } });
  driving.search(start, end);

  geolocation.getCurrentPosition(function (r) {
    if (this.getStatus() == BMAP_STATUS_SUCCESS) {
      newPoint.value =r.point;
      const mk = new BMapGL.Marker(newPoint.value);
      map.addOverlay(mk);
      map.panTo(newPoint.value);
    }
    else {
      alert('failed' + this.getStatus());
    }
  });

})
</script>
<style lang='less' scoped>
#myMap {
  height: 300px;
  width: 300px;
}
</style>
